package com.example.libraryapp.activity.login;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.example.libraryapp.Constant;
import com.example.libraryapp.R;
import com.example.libraryapp.activity.register.RegisterActivity;
import com.example.libraryapp.bean.User;
import com.example.libraryapp.bean.response.BaseResponse;
import com.example.libraryapp.network.base.BaseActivity;
import com.example.libraryapp.network.net.RetrofitException;
import com.example.libraryapp.util.LoginUtil;
import com.example.libraryapp.util.ToastUtil;
import com.example.libraryapp.widget.CnToolbar;

/**
 * @author 伍凯铭
 * @since 2020/6/17
 */
public class LoginActivity extends BaseActivity<LoginContract.View,LoginPresenterIml>
        implements View.OnClickListener, LoginContract.View{

    private EditText mInputSno;

    private EditText mInputPassword;


    @Override
    protected void initToolBar(CnToolbar toolbar) {
        toolbar.setTitle("登录");
        toolbar.setBackBtnOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.to_register_btn:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.login_btn:
                login();
                break;
        }
    }

    private void login() {
        String sno = mInputSno.getText().toString();
        String password = mInputPassword.getText().toString();
        if(TextUtils.isEmpty(sno)){
            ToastUtil.showToast(this,"学生号不能为空");
            return;
        }
        if(TextUtils.isEmpty(password)) {
            ToastUtil.showToast(this,"密码不能为空");
            return;
        }
        showLoading();
        mPresenter.doLogin(sno,password);
    }

    @Override
    protected void initView(View view) {
        view.findViewById(R.id.to_register_btn).setOnClickListener(this);
        view.findViewById(R.id.login_btn).setOnClickListener(this);
        mInputSno = view.findViewById(R.id.input_sno);
        mInputPassword = view.findViewById(R.id.input_password);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected LoginPresenterIml initPresenter() {
        return new LoginPresenterIml();
    }

    @Override
    public void showLogin(BaseResponse<User> response) {
        ToastUtil.showToast(this,response.getMessage());
        if(response.getCode() == Constant.SUCCESS_CODE) {
            LoginUtil.login(this,response.getResult());
            finish();
        }
    }

    @Override
    public void showNoNetwork(RetrofitException.ResponseThrowable error) {
        showContent();
        ToastUtil.showToast(this,error.message);
    }
}
